<?php

//检查是否wap访问
function check_wap() {

    return @stristr($_SERVER['HTTP_VIA'],"wap") ? true : false;
}

/*得到精确时间*/
function getmicrotime() {
    list($usec, $sec) = explode(" ",microtime());
    return ((float)$usec + (float)$sec);
} 
function get_use_time($min=false) {
    global $time_start;
    $time_end = getmicrotime();
    $times = $time_end - $time_start;
    $times = sprintf('%.5f',$times);
    if($min==false) {
        $use_time =  "用时:". $times ."秒";
    }else {
        $use_time = $times;
    }
    return $use_time;
}
/**
 * 想尽办法获取在线IP
 * @return <type>
 */

function get_onlineip() {
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $onlineip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $onlineip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $onlineip = $_SERVER['REMOTE_ADDR'];
    }
    return $onlineip;
}
/*function __autoload($class) {
    $classFile = SITE_ROOT."/includes/".$class.".class.php";
    if(file_exists($classFile)) {
        include_once($classFile);
    }
}*/
function __autoload($class) {
    $classFile = CLASS_ROOT."/".$class.".class.php";
    if(file_exists($classFile)) {
        include_once($classFile);
    }
}

function get_lang($str){
	return $str;
}
function tpl_lang($str,$lang=''){
	return get_lang($str,$lang);
}

//作者：longbill (longbill.cn#gmail.com)   
function make_insert_sql($table,$data) {
    $cols = array();
    $vals = array();
	if(!$GLOBALS['magic_quotes_gpc']){
		foreach($data as $key => $val) {
			$cols[] = "`$key`";
			$vals[] = "'".mysql_escape_string($val)."'";
		}
    }else{
		foreach($data as $key => $val) {
			$cols[] = "`$key`";
			$vals[] = "'".($val)."'";
		}
		
	}
    return "INSERT INTO `$table` (".join(',',$cols).") VALUES(".join(',',$vals).") ";
}   

function make_select_sql($table,$data = array(),$_select = '*') {
    $cond = array();
	if(!$GLOBALS['magic_quotes_gpc']){
    	foreach($data as $key => $val)
        $cond[] = "`$key` = '".mysql_escape_string($val)."' ";
	}else{
		foreach($data as $key => $val)
        $cond[] = "`$key` = '".($val)."' ";
	}
    $sql = "SELECT $_select FROM `$table` ";
    if (count($cond) > 0)
        $sql.= " WHERE ".join(' AND ',$cond);
    else
        $sql.= " WHERE 1=1 ";
    return $sql;
}   

function make_update_sql($table,$data,$cond_arr) {
    $values = array();
    $cond = array();
	if(!$GLOBALS['magic_quotes_gpc']){
		foreach($data as $key => $val)
			$values[] = "`$key` = '".mysql_escape_string($val)."'";
		foreach($cond_arr as $key => $val)
			$cond[] = "`$key` = '".mysql_escape_string($val)."'";
	}else{
		foreach($data as $key => $val)
			$values[] = "`$key` = '".($val)."'";
		foreach($cond_arr as $key => $val)
			$cond[] = "`$key` = '".($val)."'";		
	}
    return "UPDATE `$table` SET ".join(',',$values)." WHERE ".join(' AND ',$cond);
} 

function cache_delete($file,$path = '') {
    if(!$path) $path = CACHE_PATH;
    $cachefile = $path.$file;
    return @unlink($cachefile);


}

/**
 * 缓存读取
 */
function cache_read($file, $path = '', $iscachevar = 0) {
    if(!$path) $path = CACHE_PATH;
    $cachefile = $path.$file;
    if($iscachevar) {
        global $TEMP;
        $key = 'cache_'.substr($file, 0, -4);
        return isset($TEMP[$key]) ? $TEMP[$key] : $TEMP[$key] = @include $cachefile;
    }
    return @include $cachefile;
}
/*缓存文件*/
function cache_write($file, $array, $path = '') {
//echo '使用cache';
    if(!is_array($array)) return false;
    $array = "<?php\nreturn ".var_export($array, true).";\n?>";
    $cachefile = chk_dir($path ? $path : CACHE_PATH).$file;
    $strlen = file_put_contents($cachefile, $array);
    //echo $cachefile;

    chmod($cachefile, 0777);
    return $strlen;
}

/*是否存在缓存文件，过期时间默认20秒*/
function cache_isset($file,$expired_time=20, $path = '') {
    if(!$path) $path = CACHE_PATH;
    $cachefile = $path.$file;
    //1260763476 - 1260761474
    //echo time() .' - '.@filectime($cachefile) ;
    if (time() - @filectime($cachefile) < $expired_time) {
        return true;  //未过期
    }else {
        @unlink($cachefile) ;
        return false;
    }

}

//检查一个目录,如果不存在就建立
function chk_dir($dir) {
    if(!is_dir($dir)) {
        @mkdir($dir,0777,true);
       //Directory($dir);
    }
    return $dir;
}
function directory($dir) {

    return is_dir($dir) or (Directory(dirname($dir)) and mkdir($dir, 0777));

} 
/*分页函数*/
function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $autogoto = TRUE, $simple = FALSE) {
	global $maxpage;
	$ajaxtarget = !empty($_GET['ajaxtarget']) ? " ajaxtarget=\"".dhtmlspecialchars($_GET['ajaxtarget'])."\" " : '';

	$multipage = '';
	
	
	if($mpurl== -1 ){//自动判断当前页参数
		@reset($_GET);
		while (list($key, $val) = @each($_GET)){
			if ($key<>"page" && $key<>"action" && $key<>"Submit"){
				if (is_array($val))
				{
					$i = 0;
					foreach($val as $keyx => $valx)
					{
						$urlparameter .= "&".$key."[$i]=".urlencode($valx);
						$i++;
					}
				}
				else
					$urlparameter .= "&{$key}=".urlencode($val);
			}
		}
		$mpurl = $_SERVER['SCRIPT_NAME']."?action=".$_GET['action'].$urlparameter;

	}

	
	
	$mpurl .= strpos($mpurl, '?') ? '&' : '?';
	$realpages = 1;
	if($num > $perpage) {
		$offset = 2;

		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if($to - $from < $page) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}
		

		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="first"'.$ajaxtarget.'>1 ...</a>' : '').
			($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="prev"'.$ajaxtarget.'>&lsaquo;&lsaquo;</a>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' :
				'<a href="'.$mpurl.'page='.$i.($ajaxtarget && $i == $pages && $autogoto ? '#' : '').'"'.$ajaxtarget.'>'.$i.'</a>';
		}

		$multipage .= ($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next"'.$ajaxtarget.'>&rsaquo;&rsaquo;</a>' : '').
			($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="last"'.$ajaxtarget.'>... '.$realpages.'</a>' : '').
			(!$simple && $pages > $page && !$ajaxtarget ? '<kbd><input type="text" name="custompage" size="3" onkeydown="if(event.keyCode==13) {window.location=\''.$mpurl.'page=\'+this.value; return false;}" /></kbd>' : '');

		//$multipage = $multipage ? '<div class="pages">'.$multipage.'</div>' : '';
		$multipage = $multipage ? '<table><tr><td>Total:'.$num.' Page:'.$pages.'&nbsp;&nbsp;&nbsp;</td><td><div class="pages">'.$multipage.'</div></td></tr></table>' : '';
		//$multipage = $multipage ? '<div class="pages">'.(!$simple ? '<em>&nbsp;'.$num.'&nbsp;</em>' : '').$multipage.'</div>' : '';
	}
	$maxpage = $realpages;
	return $multipage;
}

function ispage($number) {
	return !empty($number) && preg_match ("/^([0-9]+)$/", $number);
}

function text2wml($content) {
        // 将 WML 变量前缀"$"转义
       $content = str_replace('$', '$$', $content);
       // 转换特殊字符，并将 Windows/DOS 换行符（）转化为 Unix 换行符（）
       $content = str_replace(" ", " ", htmlspecialchars($content));
       // 通过换行符来将各行分开进行处理（过滤空行）
       $content = explode(" ", $content);
        for ($i = 0; $i < count($content); $i++) {
           // 过滤首尾空格
           $content[$i] = trim($content[$i]);
           // 如果去掉全角空格为空行，则设为空行，否则不对全角空格过滤。
           if (str_replace("　", "", $content[$i]) == "") $content[$i] = "";
        }
       //合并各行，转化为 WML，并过滤掉空行
       $content = str_replace("<p><br /></p> ", "", "<p>".implode("<br /></p> <p>", $content)."<br /></p> ");
        return $content;
    }
//本篇文章来源于：开发学院 http://edu.codepub.com   原文链接：http://edu.codepub.com/2010/0109/19541.php      
    function html2wml($content) {
       // 过滤掉样式表和脚本
       $content = preg_replace("/<style .*?<\/style>/is", "", $content);
       $content = preg_replace("/<script .*?<\/script>/is", "", $content);
       // 首先将各种可以引起换行的标签（如<br />、<p> 之类）替换成换行符" "
       $content = preg_replace("/<br \s*\/?\/>/i", " ", $content);
       $content = preg_replace("/<\/?p>/i", " ", $content);
       $content = preg_replace("/<\/?td>/i", " ", $content);
       $content = preg_replace("/<\/?div>/i", " ", $content);
       $content = preg_replace("/<\/?blockquote>/i", " ", $content);
       $content = preg_replace("/<\/?li>/i", " ", $content);
       // 将" "替换为空格
       $content = preg_replace("/\ \;/i", " ", $content);
       // 某些不规范的网页中可能有" "，在普通网页中显示会按照" "显示，不会引起错误，但是在 WAP 中会原样显示，因此也要替换成空格。
       $content = preg_replace("/\ /i", " ", $content);
       // 过滤掉剩下的 HTML 标签
       $content = strip_tags($content);
       // 将 HTML 中的实体（entity）转化为它所对应的字符（WML 仅支持很有现的几个 entity），这里我转化的是中文网页，因此我指定了"GB2312"编码。
       $content = html_entity_decode($content, ENT_QUOTES, "GB2312");
       // 过滤掉不能转化的实体（entity）
       $content = preg_replace("/\&\#.*?\;/i", "", $content);
      
       // 上面是将 HTML 网页内容转化为带换行的纯文本，下面是将这些纯文本转化为 WML。
       return text2wml($content);
    }

function daddslashes($string, $force = 0) {
	if(!$GLOBALS['magic_quotes_gpc'] || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force);
			}
		} else {
			$string = addslashes($string);	//addslashes:在预定义字符前添加反斜杠；（注意；使用该函数时应先检测get_magic_quotes_gpc() ）
		}
	}
	return $string;
}
function dstripslashes($string) {

	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dstripslashes($val, $force);
		}
	} else {
		$string = stripslashes($string);
	}

	return $string;
}


function get_keywords($contents){
	$rows = strip_tags($contents);
	$arr = array(' ',' ',"\s", "\r\n", "\n", "\r", "\t", ">", "\"", "\"");
	$qc_rows = str_replace($arr, '', $rows);
	if(strlen($qc_rows)>2400){
	$qc_rows = substr($qc_rows, '0', '2400');
	}
	$contents = urlencode($contents);
	//pecho(("http://keyword.discuz.com/related_kw.html?title=$contents&ics=gbk&ocs=gbk"));
	$data = @implode('', file("http://keyword.discuz.com/related_kw.html?title=$contents&ics=gbk&ocs=gbk"));
	preg_match_all("/<kw>(.*)A\[(.*)\]\](.*)><\/kw>/",$data, $out, PREG_SET_ORDER);
	for($i=0;$i<5;$i++){
		$key=$key.$out[$i][2];
		if($out[$i][2])$key=$key.",";
	} 
	return $key; 
}
function get_keywords2($contents){
	include_once('split_word.class.php');
	//$split_word = new splitword();
	//$key = $split_word->SplitRMM($contents);
	
	
	#$keywords = "安东尼教. ~ 如何处理客户投诉 abca@sad.com 社会契约论 ABC 王国荣三元化思维，全班同学都喜刷刷";
	#$keywords = '这是二十五万元人民币，您收好！大家一起喜洋洋过新年，只有他还在疯疯癫癫在玩。不知道金山软件有没有奔头，好久都没动静了。';
	$contents = strip_tags($contents);
	$sp = new SplitWord();#中文分词类
	$key = $sp->SplitRMM($contents,TRUE,TRUE); //ReviseString,SplitRMM
	//echo $keywords;
	#if($sp->IsWord('三万'))echo '三万在字典中！';
	$sp->Clear(); #清理字典占用资源。
	$sp = null;

	
	return $key;
}
function tags($key){
	//pecho($key);
	//preg_match_all('/([^,]+)/is',$key,$match);
	//pecho($match);
	$key = preg_replace('/([^,]+)/is','<a href="javascript:top.show_tags(\'\\1\')">\\1</a>',$key);
	$key = trim($key,',');
	return $key;
	//$key = trim($key,',');
	//$key = explode(',',$key);
	//foreach($key as $k=>$v);
}
function set_radio($v1,$v2){
	if($v1==$v2){
		return 'checked';
	}
}
function set_select($v1,$v2){
	//pecho($v1.'=='.$v2.' && '.(strlen($v1)).'=='.(strlen($v2)));
	if($v1==$v2 && strlen($v1)==strlen($v2)){
		return 'selected="selected"';
	}
}
/**
* 格式化输出数组等
*/

function pecho($s,$f='print_r',$level=0) {
	static $i;
	$i++;	
	//echo '<pre>';
	//debug_print_backtrace();
	$str ='';
	if(!in_array($f,array('br','p','li'))){
		if($i<2){
			$str .="<style>
			#pecho_box{border:#CCC 1px solid; background:#FEFEED; margin:5px;padding:5px;clear:both}
			#pecho_box ul{padding-left:15px; margin-bottom: 12px;list-style:disc outside none; }#pecho_box ul li{list-style:disc outside none;}
			#pecho_box>div{border:#EFEFEF 1px solid; background:#DFDFDF; margin:-4px;padding:3px}
				
			</style>";
		}
		$str .="<pre id=\"pecho_box\" class=\"pecho_box\">\r\n";
	}
	
	if($level==1){
		$str .="<div style=\"\"><strong>$i:</strong>";	
		
		if (function_exists('debug_backtrace')) {
			$traces = debug_backtrace();
			
			//array_shift($traces);
			$trace = array_shift($traces);
			$trace['file'] = str_replace(SITE_ROOT,'',$trace['file']);
			$str .= $trace['file'].':'. $trace['line']."\r\n";
		}	 
	
		$str .="</div>";
	}
    if($f=='var_export') {
        $str .=var_export($s,true);
	}elseif($f=='var_dump'){
		$str .=var_dump($s,true);
	}elseif($f=='trace'){	
	  //debug_print_backtrace();
	  if (function_exists('debug_backtrace')) {
		$trace = debug_backtrace();
		array_shift($trace);
	  }
	 
	  $str .= pecho_trace($trace);		
//	  foreach($trace as $k=>$v){
//		$str .='#'.$k.'<font color="green" >'.$v['function']. '</font><font color="blue">(</font>'. implode(',',$v['args']) .'<font color="blue">)</font> <strong>called at</strong> ['. $v['file'] .':'. $v['line'].']'."\r\n";
//	  }
	}elseif($f=='br'){	
		$str .=$s.'<br />';
	}elseif(in_array($f,array('p','li'))){	
		$str .='<'.$f.'>'.$s.'</'.$f.'>';
		
    }else {
		
        $str .=print_r($s,true);
    }
	if(!in_array($f,array('br','p','li'))){
    	$str .= "\r\n</pre>";
	}
    echo $str;
}
function pecho_trace($traces,$level=0){
	
	static $domain = '';
	if(!is_array($traces[0])) return;
	$trace = array_pop($traces);
	
	if($level==0) {
		$tmp = pathinfo($trace['file']);
		$domain =  dirname($trace['file']);;
		$str = '<ul>';
		$str .= '<li>'.$trace['file'].'</li>';
		$str .= '<li>#'. $level.' {main}';
	}
	if(in_array($trace['function'],array('require','require_once','include','include_once'))){
		
		$fullpath = $trace['args'][0];
		$path = dirname($fullpath);
		$file = basename($fullpath);
		//$trace['args'][0] = str_replace($domain,'',$trace['args'][0]);
		$trace['args'][0] = '<a target="_blank" title="'.$fullpath.'" href="file:///'.str_replace(':',':',$path).'">'.str_replace(array($domain,'\\'),array('','/'),$path).'</a>/<a target="_blank" title="'.$fullpath.'"  href="file:///'.str_replace(':',':',$fullpath).'">'.$file.'</a>';
		
		$str .= '<ul>';
		$str .= '<li>';
		$str .= 'Line:'. $trace['line'].' <font color="green" >'.$trace['function']. '</font><font color="blue">(</font>'.  implode(',',$trace['args']) .'<font color="blue">)</font> ';
		$str .= pecho_trace($traces,++$level);
		$str .=  '</li>';
		$str .=  '</ul>';
	}else{
		$str .= '<ul>';
		$str .= '<li>';
		$str .= 'Line:'. $trace['line'].' <font color="blue" >PHP::'.$trace['function']. '</font><font color="blue">(</font>'. implode(',',$trace['args']) .'<font color="blue">)</font> ';
		$str .= pecho_trace($traces,++$level);
		$str .=  '</li>';
		$str .=  '</ul>';
	}
	if($level==0) {
		$str .=  '</li>';
		$str .=  '</ul>';
	}
	return $str;
	
}

    /**
     * 更新某个会员某个时间后所有帐目的小计
     * @param String $username
     * @param INT $date
     */
    function update_statement_net($uid,$date=0,$ccy='CNY') {
		global $db,$tablepre;
		$datesql ='';
        if($date) {
            $datesql .= " AND update_date>='$date'";
        }
		if($ccy) {
            $datesql .= " AND ccy>='$ccy'";
        }
		
        $sql = "SELECT * FROM {$tablepre}book WHERE uid='$uid' $datesql ORDER BY update_date ASC,id ASC";
        //$sql = "SELECT * FROM ".TABLE_STATEMENT." WHERE username='$username' $datesql ORDER BY id ASC";
       //pecho('sql:'.$sql);
        $arrs = $db->fetch_all($sql);
        if($arrs) {
            foreach($arrs as $k=>$v) {
                if($k>0) {
                    $arrs[$k]['net'] = $arrs[$k-1]['net']+$v['amount'];
                }else {
                    $arrs[$k]['net']=$v['net'];
                }
                $id = $v['id'];
                $net = $arrs[$k]['net'];
                $sql ="UPDATE  {$tablepre}book SET net =$net WHERE id=$id";
				//pecho ($v);
               // pecho ('net:'.$sql);
                 $db->query($sql);
                //pecho($sql);
            }
        }

    }
	
	/*
函数: Pager
作者: Sam Teng <[email=samteng@live.com]samteng@live.com[/email]>
作用：通过记录总数，每页显示数取得offset，总页数，前一页与后一页以及分页纯数字的页数数组，不带任何链接
返回值: 数组
$aPageDatas['offset']        offset 
$aPageDatas['thispage']      当前页 
$aPageDatas['maxpage']       总页数 
$aPageDatas['prepage']       上一页 
$aPageDatas['nextpage']      下一页
$aPageDatas['pagebar']       分页数组
$aPageDatas['pregroup']      上一组页码
$aPageDatas['nextgroup']     下一组页码
$aPageDatas['querystring']   QUERY_STRING 

参数说明:
$intTotal     记录总数
$intShowNum   每页显示数
$intDistance  分页数组最大最小值与当前页的差值,当0或false的时候，不构建分页数组
$strPageVar   分页变量名，在地址档中如abc.php?page=123，即是page，默认是'page'
$bGetQueryString  是否读取Query String, 默认读取
*/
function Pager ( $intTotal , $intShowNum ,  $intDistance = 5 , $strPageVar = 'page' ,  $bGetQueryString = true ) {
    $aPageDatas = array() ;
    ( $intThisPage = intval( $_REQUEST[$strPageVar] ) ) > 1 ? $aPageDatas[thispage] = $intThisPage : $aPageDatas['thispage'] = $intThisPage = 1 ;
    if ( $intTotal < 1 || $intShowNum < 1 ) {
        $intOffset   = 0 ;
        $aPageDatas['maxpage']  = $aPageDatas['prepage'] = $aPageDatas['nextpage'] = 1 ;
		$aPageDatas['offset']=0;
        return $aPageDatas ;
    }
    $aPageDatas['total']  =$intTotal;//总
    $aPageDatas['show_num']  =$intShowNum;//每
    $aPageDatas['offset']   = $intShowNum * ( $intThisPage - 1 ) ;
    $aPageDatas['maxpage']  = ceil ( $intTotal / $intShowNum ) ;
    $aPageDatas['prepage']  = $intThisPage < 2 ? 1 : $intThisPage - 1 ;
    $aPageDatas['nextpage'] = $intThisPage == $aPageDatas['maxpage'] ? $aPageDatas['maxpage']  : $intThisPage + 1 ;
    if ( $intDistance ) {
        $arrPageBar = array() ;
        $intSPage = ( $intThisPage - $intDistance ) < 1 ? 1 : ( $intThisPage - $intDistance ) ;
        $intEPage = ( $intThisPage + $intDistance ) > $aPageDatas['maxpage'] ? $aPageDatas['maxpage'] : ( $intThisPage + $intDistance ) ;
        $arrPageBar = array ( ) ;
        for ( $i = $intSPage ; $i <= $intEPage ; $i++ ) {
            $arrPageBar[] = $i ;
        }
        $aPageDatas['pagebar']   = $arrPageBar ;
        $aPageDatas['pregroup']  = $intThisPage > ( $intDistance + 1 ) ? $intThisPage - ( $intDistance + 1 ) : 0 ;
        $aPageDatas['nextgroup'] = $intThisPage < ( $aPageDatas['maxpage'] - 1 - $intDistance ) ? $intThisPage + $intDistance + 1 : $aPageDatas['maxpage'] ;
    }
    if ( $bGetQueryString ) {


        $tmp  = explode('?',$_SERVER['REQUEST_URI']);
        $_SERVER["QUERY_STRING"] = $tmp[1] ;


        $strPagepattern = '/('.$strPageVar.'=\d{0,})/' ;
        preg_match_all( $strPagepattern, $_SERVER["QUERY_STRING"] , $arrResult );
        $strQueryString = $arrResult[1][0] ? str_replace( "&".$arrResult[1][0] , "" , $_SERVER["QUERY_STRING"] ) : $_SERVER["QUERY_STRING"];
        $strQueryString = str_replace( $arrResult[1][0] , "" , $strQueryString ) ;
        if ( $strQueryString ) $aPageDatas['querystring'] = $strQueryString . '&';
    }
    return $aPageDatas ;
}

function show_pagenav($aPageDatas) {

    $querystring =$aPageDatas['querystring'];
    $total =$aPageDatas['total'] ;
    $firstcount = 	$aPageDatas['offset'];
    $prepg = $aPageDatas['prepage'];
    $nextpg = $aPageDatas['nextpage'];
    $displaypg = $aPageDatas['show_num'] ;
    $lastpg = $aPageDatas['maxpage'];
    $page = $aPageDatas['thispage'];


//开始分页导航条代码：  
//$total总数
//$displaypg每 页显示条
    //$page =$_GET['page'];
    $pagenav="显示第 <B>".($total?($firstcount+1):0)."</B>-<B>".min($firstcount+$displaypg,$total)."</B> 条记录，共 $total 条记录<BR>";
    //如果只有一页则跳出函数：
    if($lastpg<=1) {
        return false;
    }
    // $url='';
    $url.= '?'. $querystring . "&page";
    $url = str_replace('&&','&',$url);
    /*  if(strstr($querystring,'?')){
	
  }else {  
  	$url.="?page";  
  }  */

    $pagenav.=" <a href=\"$url=1\">首页</a> ";
    if($prepg) {
        $pagenav.=" <a href=\"$url=$prepg\">前一页</a> ";
    }else {
        $pagenav.=" 前页 ";
    }

    if($nextpg) {
        $pagenav.=" <a href=\"$url=$nextpg\">后一页</a> ";
    }else {
        $pagenav.=" 后页 ";
    }
    $pagenav.=" <a href=\"$url=$lastpg\">尾页</a> ";
    //下拉跳转列表，循环列出所有页码：
    $pagenav.="　转到第 <select name=\"topage\" size=\"1\" onchange=\"window.location='$url='+this.value\">\n";
    for($i=1;$i<=$lastpg;$i++) {
        if($i==$page) {
            $pagenav.="<option value=\"$i\" selected>$i</option>\n";
        }else {
            $pagenav.="<option value=\"$i\">$i</option>\n";
        }
    }
    $pagenav.="</select> 页，共 $lastpg 页";
    return $pagenav;
}
	function update_path($id){
		global $db,$tablepre;

		$sql = "SELECT id,pid,path FROM {$tablepre}channel WHERE id = (SELECT pid FROM {$tablepre}channel WHERE id=$id) ";
		$ppath = $db->fetch_first($sql);
		if($ppath['path']){//有上级，并且上级设置了path					
			$path  = $ppath['path'].','. str_pad($id,5,'0',STR_PAD_LEFT);
		}elseif($ppath['id']){//上级分类有，但没有设置path时
			 update_path($ppath['id']);
			 update_path($id);
			 return;
		}else{
			$path = ','.str_pad($id,5,'0',STR_PAD_LEFT);
		}
	
			
		$dbarr['path'] = $path;
		$where['id'] = $id;
		$sql = make_update_sql("{$tablepre}channel",$dbarr,$where);
		$db->query($sql);
	}
	//得到导航路径，根据分类ID
	function get_nav($pid){
		global $db,$tablepre;
		if(!$pid){
			return;
		}
		$sql = "SELECT * FROM {$tablepre}channel WHERE id = ".$pid;
		$pinfo = $db->fetch_first($sql);		
		$path = preg_replace('/[0]+/is','',$pinfo['path']);
		$path = trim($path,',');
		if(!$path){
			update_path($pid);
			return get_nav($pid);
		}
		$sql = "SELECT * FROM {$tablepre}channel WHERE id IN($path)";
		$pinfos = $db->fetch_all($sql);
		foreach($pinfos as $k=>$v){
			$nav .= '<a href="view_channel.php?id='.$v['id'].'">'.$v['name'].'</a>&gt;&gt;';
		}
		return $nav;
	}
function substr2($str, $start, $length = false, $encoding = 'utf-8')
	{
		if (is_array($str))
			return false;
		if (function_exists('mb_substr'))
			return mb_substr($str, intval($start), ($length === false ? self::strlen($str) : intval($length)), $encoding);
		return substr($str, $start, ($length === false ? strlen($str) : intval($length)));
	}	
?>